package constant.milk.toilet.setting;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import constant.milk.toilet.IntroActivity;
import constant.milk.toilet.MainActivity;
import constant.milk.toilet.R;
import constant.milk.toilet.SuperActivity;
import constant.milk.toilet.database.DbAdapter;
import constant.milk.toilet.dialog.MilkDialog;
import constant.milk.toilet.dialog.MilkThreeDialog;
import constant.milk.toilet.util.MilkUtil;

public class BackUpActvitiy extends SuperActivity
{
	private String dirName;
	
	private TextView preView;
	private TextView titleTextView;
	
	private TextView listTitleTextView;
	
	private ListView listView;
	
	private View saveView;
	private TextView saveTextView;
	
	private String fileName;
	
	private MilkDialog dialog;
	private MilkThreeDialog threeDialog;
	
	private File [] readFiles;
	
	private File selectFile;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.bankup_activity);
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		preView = (TextView) findViewById(R.id.backUpPreTextView);
		titleTextView = (TextView) findViewById(R.id.backUpTitleTextView);
		
		listTitleTextView = (TextView) findViewById(R.id.backUpListTitleTextView);
		listView = (ListView) findViewById(R.id.listView);
		
		saveView = findViewById(R.id.backUpSaveView);
		saveTextView = (TextView) findViewById(R.id.backUpSaveTextView);
	}

	@Override
	protected void setOnClick()
	{
		preView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		
		saveView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (setSaveData())
				{
					dialog = new MilkDialog(superContext, 
							"백업에 성공 하였습니다.", 
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									setData();
									dialog.dismiss();
								}
							}, 
							null);
					dialog.setLeftTitle("확인");
				}
				else
				{
					dialog = new MilkDialog(superContext, 
							"백업에 실패 하였습니다. 개발자에게 문의 해주세요.", 
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									dialog.dismiss();
								}
							}, 
							null);
					dialog.setLeftTitle("확인");
				}
				
				if (dialog != null)
				{
					dialog.show();
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		titleTextView.setTextColor(Color.WHITE);
		titleTextView.setTextSize(TEXT_SIZE + 2);
		
		listTitleTextView.setTextColor(Color.WHITE);
		saveTextView.setTextColor(Color.WHITE);
		
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DAY_OF_MONTH);
		String time = cal.get(Calendar.HOUR_OF_DAY) + "" + cal.get(Calendar.MINUTE) + "" + cal.get(Calendar.SECOND);
		
		String date = MilkUtil.getDateFile(year, month+1, day);
		
		date = date.replace(" ", "");
		
		dirName = getString(R.string.app_name);
		fileName = getString(R.string.app_name) + "_" + date + "_" + time;
		
		ArrayList<File> list = new ArrayList<File>();
		
		try
		{
			File directory = new File(Environment.getExternalStorageDirectory() + "/" 
										+ dirName);
			
			readFiles = directory.listFiles(new FilenameFilter()
			{
				@Override
				public boolean accept(File dir, String filename)
				{
					return filename.endsWith(".db");
				}
			});
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		
		if (readFiles != null)
		{
			for (int i = readFiles.length - 1; i > -1 ; i--)
			{
				list.add(readFiles[i]);
			}
		}
		
		listView.setOnItemClickListener(onItemClickListener);
		
		BackUpAdapter listAdapter = new BackUpAdapter(
				superContext, R.layout.list_item_normal, list);
		listView.setAdapter(listAdapter);
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			selectFile = (File) arg0.getItemAtPosition(position);
			
			threeDialog = new MilkThreeDialog(superContext, 
					"파일을 복구, 삭제 하실 수 있습니다.", 
					new OnClickListener()
					{
						@Override
						public void onClick(View v)
						{
							threeDialog.dismiss();
							
							showRollBackDialog();
						}
					}, 
					new OnClickListener()
					{
						@Override
						public void onClick(View v)
						{
							threeDialog.dismiss();
							
							showDeleteDialog();
						}
					},
					new OnClickListener()
					{
						@Override
						public void onClick(View v)
						{
							threeDialog.dismiss();
						}
					});
			
			threeDialog.setLeftTitle("복구");
			threeDialog.setMiddleTitle("삭제");
			threeDialog.setRightTitle("취소");
			
			threeDialog.show();
		}
	};
	
	private void showDeleteDialog()
	{
		if (setDelete(selectFile))
		{
			dialog = new MilkDialog(superContext, 
					"삭제에 성공 하였습니다.", 
					new OnClickListener()
					{
						@Override
						public void onClick(View v)
						{
							dialog.dismiss();
							setData();
						}
					}, 
					null);
			dialog.setLeftTitle("확인");
			dialog.show();
		}
		else
		{
			dialog = new MilkDialog(superContext, 
					"삭제에 실패 하였습니다. 개발자에게 문의 해주세요.", 
					new OnClickListener()
					{
						@Override
						public void onClick(View v)
						{
							dialog.dismiss();
						}
					}, 
					null);
			dialog.setLeftTitle("확인");
			dialog.show();
		}
	}
	
	private void showRollBackDialog()
	{
		if (setRollBankData(selectFile))
		{
			dialog = new MilkDialog(superContext, 
					"복구에 성공 하였습니다.", 
					new OnClickListener()
					{
						@Override
						public void onClick(View v)
						{
							dialog.dismiss();
							Intent intent = new Intent(superContext, MainActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
							startActivity(intent);
							finish();
						}
					}, 
					null);
			dialog.setLeftTitle("확인");
			dialog.show();
		}
		else
		{
			dialog = new MilkDialog(superContext, 
					"복구에 실패 하였습니다. 개발자에게 문의 해주세요.", 
					new OnClickListener()
					{
						@Override
						public void onClick(View v)
						{
							dialog.dismiss();
						}
					}, 
					null);
			dialog.setLeftTitle("확인");
			dialog.show();
		}
	}

	private boolean setSaveData()
	{
		DbAdapter adapter = DbAdapter.getInstance();
		String path = adapter.getDbPath(superContext);
		adapter.close();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try
		{
			File readfile = new File(path);
			
			if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
			{
				return false;
			}
			
			fis = new FileInputStream(readfile);
			
			File directory = new File(Environment.getExternalStorageDirectory() + "/" + dirName);
			
			if (!directory.exists())
			{
				directory.mkdir();
			}
			
			String directoryPath = directory.getPath();
			
			File writefile = new File(directoryPath + "/" + fileName + ".db");
			
			fos = new FileOutputStream(writefile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return false;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
			} catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setDelete(File selectFile)
	{
		if (selectFile == null)
		{
			return false;
		}
		
		String filePath = "";
		
		filePath = "/" + dirName + "/";
		
		File file = new File(Environment.getExternalStorageDirectory() + filePath + selectFile.getName());
		
		return file.delete();
	}
	
	private boolean setRollBankData(File selectFile)
	{
		if (selectFile == null)
		{
			return false;
		}
		
		DbAdapter adapter = DbAdapter.getInstance();
		String path = adapter.getDbPath(superContext);
		adapter.close();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		
		try
		{
			String filePath = selectFile.getPath();
			SQLiteDatabase db = SQLiteDatabase.openDatabase(filePath, 
					null, SQLiteDatabase.CREATE_IF_NECESSARY);
			
			if (!db.isOpen())
			{
				return false;
			}
			
			db.close();
			
			fis = new FileInputStream(selectFile);
			
			File writeFile = new File(path);
			
			fos = new FileOutputStream(writeFile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return false;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
			} catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	public class BackUpAdapter extends ArrayAdapter<File>
	{

		public BackUpAdapter(Context context, int resource, List<File> objects)
		{
			super(context, resource, objects);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null) 
			{
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.list_item_normal, null);
			}
			
			File data = getItem(position);
			
			TextView tv = (TextView) v.findViewById(R.id.listItemNormalTextView);
			
			tv.setTextSize(TEXT_SIZE);
			
			tv.setText(data.getName());
			
			return v;
		}
	}
}
